//
//  GZJDBViewController.m
//  Estate
//
//  Created by heyong on 16/5/26.
//  Copyright © 2016年 ttsx. All rights reserved.
//
#define DIC_EXPANDED @"expanded" //是否是展开 0收缩 1展开
#define DIC_ARARRY @"array"
#define DIC_TITILESTRING @"title"
#define CELL_HEIGHT 46.0f

#import "FollowIncell.h"
#import "addJGDBViewController.h"
#import "DBYSDetailViewController.h"
#import "SGFYSViewController_detail.h"

#import "GZJDBViewController.h"


@interface GZJDBViewController ()<UITableViewDelegate,UITableViewDataSource>

//表格
@property(strong, nonatomic)UITableView *tableView;
//数据
@property(strong ,nonatomic)NSMutableArray *DataArray;
//添加按钮
@property (strong, nonatomic)UIButton *addBtn;

@end



@implementation GZJDBViewController

-(UITableView *)tableView{
    
    if(_tableView==nil){
        _tableView=[[UITableView alloc]initWithFrame:CGRectMake(0, 0, DEF_SCREEN_WIDTH, DEF_SCREEN_HEIGHT-44-49-50*BIZ)];
        _tableView.delegate=self;
        _tableView.dataSource=self;
        _tableView.tableFooterView=[[UIView alloc]initWithFrame:CGRectZero];
        _tableView.backgroundColor=[UIColor colorWithRed:0.97 green:0.97 blue:0.97 alpha:1.00];
       [_tableView registerNib:[UINib nibWithNibName:@"FollowInCell" bundle:nil] forCellReuseIdentifier:@"follCell"];
    }
    return _tableView;
}

- (NSMutableArray *)DataArray {
    if (!_DataArray) {
        _DataArray = [[NSMutableArray alloc] init];
    }
    return _DataArray;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.view addSubview:self.tableView];
    self.view.backgroundColor=[UIColor colorWithRed:0.97 green:0.97 blue:0.97 alpha:1.00];
    
    [self createView1];
    [self initDataSource];
    
    // 添加通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshData) name:@"refreshDuBList" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshData) name:@"reloadData" object:nil];
}

- (void)refreshData {
    [self.DataArray removeAllObjects];
    [self initDataSource];
    [self.tableView reloadData];
}

//创建添加btn
- (void)createView1 {
    self.addBtn=[[UIButton alloc]initWithFrame:CGRECTS(260, 360, 100, 100)];
    [_addBtn setImage:[UIImage imageNamed:@"add_2"] forState:UIControlStateNormal];
    [self.view addSubview:_addBtn];
    [_addBtn addTarget:self action:@selector(addMethold) forControlEvents:UIControlEventTouchUpInside];
}

#pragma MARK - 添加督办
- (void)addMethold {
    addJGDBViewController *addGJVC = [[addJGDBViewController alloc] init];
    addGJVC.isDB = YES;
    [self.navigationController pushViewController:addGJVC animated:YES];
}

//初始化数据
- (void)initDataSource
{
    FMDatabase *db=[FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    [db open];
    FMResultSet *result=[db executeQuery:SQL_PROCESS_SELECT_DB(PROID)];
    
    NSMutableDictionary *dic;
    while ([result next]) {
        // 查询到 年
        NSString* year= [result stringForColumn:@"year"];
        // 查询到月
        NSString *month =[result stringForColumn:@"month"] ;
        // 根据日期查询展开的数据
        NSString *sqlStr=[NSString stringWithFormat:@"SELECT BEGIN_TIME, ID,ADDRES_INFO, PROCESS_PUBLISHERS, EXTEND_INFO, PROCESS_TYPE, PROCESS_STAGE,PROCESS_TITLE,REQUIRED_END_TIME,time(CREATE_TIME) as time, MODIFY_TIME from PROCESS where substr(CREATE_TIME,6,2) = '%@' and pro_id = '%@' AND PROCESS_STAGE NOT IN (%d,%d) ORDER BY CREATE_TIME desc",month,PROID,PROCESS_STAGE_REVIEW_PASS_NO,PROCESS_STAGE_END];
        
        //查询到记录
        NSMutableArray *DetailArr=[NSMutableArray array];
        FMResultSet *results=[db executeQuery:sqlStr];
        while ([results next]) {
            
            NSString *title=[results stringForColumn:@"PROCESS_TITLE"];
            NSString *processId=[results stringForColumn:@"ID"];
            int state=[results intForColumn:@"PROCESS_STAGE"];
            NSString *endTime=[results stringForColumn:@"REQUIRED_END_TIME"];
            NSString *rowTime=[results stringForColumn:@"time"];
            NSString *modifyTime=[results stringForColumn:@"MODIFY_TIME"];
            // 流程类型
            int type = [results intForColumn:@"PROCESS_TYPE"];
            //位置信息
            NSString *addressInfo = [results stringForColumn:@"ADDRES_INFO"];

            // 报送人
            NSString *publisher = [results stringForColumn:@"PROCESS_PUBLISHERS"];
            
            // 发送时间
            NSString *beginTime = [results stringForColumn:@"BEGIN_TIME"];
            //时差
            NSString *shicha;
            if ([endTime isEqual:@""]) {
                shicha = @"0";
            } else {
                NSTimeInterval  timeInterval = [LSUtility getDifftimeByTime:endTime];
                long temp = timeInterval / 3600;
                if (timeInterval >= 0) {
                    temp = temp + 1;
                } else if (timeInterval < 0) {
                    temp = temp - 1;
                }
                shicha = [NSString stringWithFormat:@"%ld", temp];
            }
            
            NSDictionary *dics=@{@"id":processId,@"title":title,@"state":@(state),@"time":rowTime,@"shicha":shicha,@"modifyTime":modifyTime, @"TYPE":[NSString stringWithFormat:@"%d", type],@"publisher":publisher, @"BEGIN_TIME":beginTime,@"addressInfo":addressInfo};
            [DetailArr addObject:dics];
        }
        
        //查询到数量
        NSString *counts=[result stringForColumn:@"COUNT(*)"];
        //拼接成标题
        NSString *tiemAndCount=[NSString stringWithFormat:@"%@年%@月 (%@条)",year,month,counts];
        //创建一个字典 包含数组，分组名，是否展开的标示
        dic = [[NSMutableDictionary alloc] initWithObjectsAndKeys:DetailArr,DIC_ARARRY,tiemAndCount,DIC_TITILESTRING,[NSNumber numberWithInt:0],DIC_EXPANDED,nil];
        //将字典加入数组
        [self.DataArray addObject:dic];
    }
    [db close];
}

#pragma MARK - UITableViewDelegate,UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return _DataArray.count;
}

//设置分组头的视图
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *hView = [[UIView alloc]initWithFrame:CGRectMake(0,0, DEF_SCREEN_WIDTH, CELL_HEIGHT-10)];
    hView.backgroundColor=[UIColor colorWithRed:0.94 green:0.94 blue:0.94 alpha:1.00];
    UIButton* eButton = [[UIButton alloc] init];
    eButton.backgroundColor=[UIColor whiteColor];
    //按钮填充整个视图
    eButton.frame = hView.frame;
    [eButton addTarget:self action:@selector(expandButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
    //把节号保存到按钮tag，以便传递到expandButtonClicked方法
    eButton.tag = section;
    //根据是否展开，切换按钮显示图片
    if ([self isExpanded:section])
        [eButton setImage:  [UIImage imageNamed: @"xiala" ]forState:UIControlStateNormal];
    else
        [eButton setImage: [UIImage imageNamed: @"gengduo1" ]forState:UIControlStateNormal];
    
    //设置分组标题
    [eButton setTitle:[[_DataArray objectAtIndex:section] objectForKey:DIC_TITILESTRING]forState:UIControlStateNormal];
    
    [eButton setTitleColor:[UIColor colorWithRed:0.68 green:0.68 blue:0.68 alpha:1.00] forState:UIControlStateNormal];
    //设置字体样式
    eButton.titleLabel.font=[UIFont systemFontOfSize:14.*BIZ];
    
    //设置button的图片和标题的相对位置
    
    //4个参数是到上边界，左边界，下边界，右边界的距离
    eButton.contentHorizontalAlignment =UIControlContentHorizontalAlignmentLeft;
    [eButton setTitleEdgeInsets:UIEdgeInsetsMake(0,5, 0,0)];
    [eButton setImageEdgeInsets:UIEdgeInsetsMake(5,DEF_SCREEN_WIDTH-30, 0,0)];
    
    //添加btn
    [hView addSubview: eButton];
    return hView;
    
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    //判断是收缩还是展开
    NSMutableDictionary *dic=[_DataArray objectAtIndex:section];
    if ([[dic objectForKey:DIC_EXPANDED]intValue]) {
        return 10;
    }else{
        return 0;
    }
}

//控制表头分组表头高度
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 46*BIZ;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return 70*BIZ;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    NSMutableDictionary *dic=[_DataArray objectAtIndex:section];
    NSArray *array=[dic objectForKey:DIC_ARARRY];
    //判断是收缩还是展开
    if ([[dic objectForKey:DIC_EXPANDED]intValue]) {
        return array.count;
    }else{
        return 0;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSMutableDictionary *dic=[self.DataArray objectAtIndex:indexPath.section];
    NSArray *array=[dic objectForKey:DIC_ARARRY];
    NSDictionary *dics=array[indexPath.row];
    NSLog(@"%@",dics);
    FollowInCell *cell=[tableView dequeueReusableCellWithIdentifier:@"follCell" forIndexPath:indexPath];
    NSString *time = [dics[@"shicha"] stringByAppendingString:@"H"];
   
    int type = [dics[@"TYPE"] intValue];
 
    
    // 查询发送类型
    NSString *sql = [NSString stringWithFormat:@"SELECT SEND_TYPE FROM PROCESS_RECORD WHERE PROCESS_ID = '%@'", dics[@"id"]];
    FMDatabase *db = [FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    [db open];
    FMResultSet *resulet = [db executeQuery:sql];
    int sendType = 8;
    while ([resulet next]) {
        sendType = [resulet intForColumn:@"SEND_TYPE"];
        break;
    }
    [db close];
    
    
    [cell setTitle:dics[@"title"] andDeTime:dics[@"time"] andTime:time andState:[dics[@"state"] intValue] andProcessType:type];
    
  
    
    return cell;
}

#pragma mark-点击表格
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    NSMutableDictionary *dic = [self.DataArray objectAtIndex:indexPath.section];
    NSArray *array = [dic objectForKey:DIC_ARARRY];
    NSDictionary *dics=array[indexPath.row];
    //流程id
    NSString *processId= dics[@"id"];
    // 是否同步
    BOOL sync = [LSUtility queryProcessIsSync:processId];
    // 验收
    if ([dics[@"TYPE"] intValue] == 3){
        SGFYSViewController_detail *YSDetail = [[SGFYSViewController_detail alloc] init];
        YSDetail.processID = dics[@"id"];
        YSDetail.zongJian = YES;
        [self.navigationController pushViewController:YSDetail animated:YES];
    }

    // 督办单(待复查)未同步
   else  if ([dics[@"TYPE"] isEqualToString:@"1"] && [dics[@"state"] integerValue] == PROCESS_STAGE_CHECK && sync) {
        addJGDBViewController *addGJVC = [[addJGDBViewController alloc] init];
        //督办
        addGJVC.isDB = YES;
        addGJVC.processId = processId;
        addGJVC.edit = YES;
        //位置信息
        addGJVC.addressInfo = dics[@"addressInfo"];
        [self.navigationController pushViewController:addGJVC animated:YES];
    // 其他形式(督办单:复查通过; 跟进单:待审阅, 复查通过)
    } else {
        DBYSDetailViewController *GJDetail=[[DBYSDetailViewController alloc]init];
        GJDetail.processId = processId;
        GJDetail.addresInfo = dics[@"addressInfo"];
        GJDetail.beginTime = dics[@"BEGIN_TIME"];
        [self.navigationController pushViewController:GJDetail animated:YES];
    }
}

#pragma mark -- 内部调用
//对指定的节进行“展开/折叠”操作,若原来是折叠的则展开，若原来是展开的则折叠
-(void)collapseOrExpand:(long)section{
    NSMutableDictionary *dic=[_DataArray objectAtIndex:section];
    int expanded=[[dic objectForKey:DIC_EXPANDED] intValue];
    if (expanded) {
        [dic setValue:[NSNumber numberWithInt:0]forKey:DIC_EXPANDED];
    }else
    {
        [dic setValue:[NSNumber numberWithInt:1]forKey:DIC_EXPANDED];
    }
}

//返回指定节是否是展开的

-(int)isExpanded:(long)section{
    NSDictionary *dic=[_DataArray objectAtIndex:section];
    int expanded=[[dic objectForKey:DIC_EXPANDED] intValue];
    return expanded;
}

//按钮被点击时触发
-(void)expandButtonClicked:(id)sender{
    UIButton* btn= (UIButton*)sender;
    long section= btn.tag;//取得tag知道点击对应哪个块
    [self collapseOrExpand:section];
    //刷新tableview
    [self.tableView reloadData];
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}


@end

